package com.pic.mgt.action.shell;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;

import com.pic.mgt.action.BusinessRecoverAction;
import com.pic.mgt.action.MissUnitInspectAction;
import com.pic.mgt.telnetd.AbstractCommandPerformer;

public class BusinessRecoverCommandPerformer extends
		AbstractCommandPerformer {
	
	private final String commandName = "rcvbiz";
	private final String commandDescritpion = "recovery miss or halt business.";
	
	private BusinessRecoverAction businessRecoverActionImpl;
	
	private MissUnitInspectAction missBusinessUnitInspectAction;

	@Override
	protected void addOption(Options options) {
		options.addOption("tn", true, "assign target file name to recover. (*MUST SURE BUSINESS WAS MISSED OR HALTED.) (incompatible with 'at')");
		options.addOption("at", false, "auto-inspect miss or halt business and do recovery. (incompatible with 'tn')");
	}

	@Override
	protected String doCommandPerform(CommandLine commandLine) {
		// 如果同時有 'tn' 和 'at' 的參數,表示語意不明
		if (commandLine.hasOption("tn") && commandLine.hasOption("at")) {
			return
			super.getReplyMessageWithReplyCode("'-tn' and '-at' are incompatible.",
											   this.COMMAND_PERFORM_FAILED_CODE);
		}
		
		// ---------------------------------------
		
		if (commandLine.hasOption("tn")) {
			boolean isRecoverySuccessful = 
				this.businessRecoverActionImpl.recoverBusiness(
						commandLine.getOptionValue("tn"));

			if (isRecoverySuccessful) {
				return super.getCommandPerformFinishMsg();
			}
			else {
				return super.getCommandPerformFailedMsg();
			}
		}
		else if (commandLine.hasOption("at")) {
			boolean isAutoRecoverySuccessful = 
				this.missBusinessUnitInspectAction.inspectMissUnitAndRecover();
			
			if (isAutoRecoverySuccessful) {
				return super.getCommandPerformFinishMsg();
			}
			else {
				return super.getCommandPerformFailedMsg();
			}
		}
		else {
			return
			super.getReplyMessageWithReplyCode("did not provide recovery parameters.",
											   this.COMMAND_PERFORM_FAILED_CODE);
		}
	}

	@Override
	public String getCommandDescription() {
		return this.commandDescritpion;
	}

	@Override
	public String getCommandName() {
		return this.commandName;
	}

	public void setBusinessRecoverActionImpl(
			BusinessRecoverAction businessRecoverActionImpl) {
		this.businessRecoverActionImpl = businessRecoverActionImpl;
	}

	public void setMissBusinessUnitInspectAction(
			MissUnitInspectAction missBusinessUnitInspectAction) {
		this.missBusinessUnitInspectAction = missBusinessUnitInspectAction;
	}

}
